<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <comment-item
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @click-reply="$emit('click-reply', $event)"
    ></comment-item>
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment.js'
import CommentItem from './comment-item.vue'
import { debounce } from 'lodash'
export default {
  name: 'commentList',
  props: {
    source: {
      type: [String, Number, Object],
      require: true
    },
    type: {
      type: String,
      default: 'a',
      validator: function (value) {
        return ['a', 'c'].includes(value)
      }
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  components: {
    CommentItem
  },
  data () {
    return {
      loading: false,
      finished: false,
      offset: null,
      limit: 10
    }
  },
  created () {
    this.onLoad()
    this.loading = true
  },
  // watch: {
  //   source () {
  //     this.list.splice(0)
  //     this.onLoad()
  //     this.loading = true
  //   }
  // },
  methods: {
    onLoad: debounce(async function () {
      try {
        // 1. 请求获取数据
        const { data: { data: { results, last_id: lastId, total_count: totalCount } } } = await getComments({
          type: this.type, //  评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.source.toString(), // 源id，文章id或评论id
          offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          limit: this.limit// 获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
        })
        // 2. 将数据添加到列表中
        this.list.push(...results)
        // 把文章评论的总数量传递到外部
        this.$emit('update-total-count', totalCount)
        // 3. 将 loading 设置为 false
        this.loading = false
        // this.finished = true
        // 4. 判断是否还有数据
        if (results.length === 0) {
          // console.log(results.length)
          // 没有就将 finished 设置结束
          this.finished = true
        } else {
          // 有就更新获取下一页的数据页码
          this.offset = lastId
        }
      } catch (error) {
        console.error(error)
      }
    }, 300)
  }
}
</script>

<style lang="less" scoped>
</style>
